/**
 * Created by xwz on 2017/7/3.
 */
// 弹出窗
var urlHead='/cashier';
var SITE_LANG = localStorage.getItem('SITE_LANG');
var SITE_CONFIG = $.parseJSON(localStorage.getItem('SITE_CONFIG'));
var CASHIER = localStorage.getItem('CASHIER');

var SITE_I18N = {
	'chinese':{
		'LOGIN_NO_USER':'请输入账号',
		'LOGIN_NO_PASSWORD':'请输入密码',
		'INDEX_BILL_SUCCESS':'挂单成功',
		'INDEX_NO_SHOP':'请添加商品',
		'INDEX_NO_REMARK':'请填写备注信息',
		'INDEX_NO_PHONE':'请输入手机号码',
		 'INDEX_NO_DISCOUNT':'请填写优惠金额',
		 'INDEX_HAD_ADD':'该商品已加入购物车',
		 'INDEX_NO_USER':'未找到该用户',
		 'INDEX_DISABLED_USER':'该用户被禁用',
		 'ORDER_DELETE_SUCCESS':'挂单删除成功',
		 'INDEX_ORDER_NOT_FIND':'订单未找到',
		 'INDEX_ORDER_PAY':'支付方式错误',
		 'INDEX_ORDER_MONEY':'支付金额错误',
		 'INDEX_ORDER_SUCCESS':'支付成功',
		 'INDEX_ORDER_FAIL':'创建订单失败',
		 'INDEX_ORDER_NUM':'商品和数量填写不正确',
		 'INDEX_SELECT_PAY':'请选择支付方式',
		 'INDEX_SEARCH_PLACE':'请扫描商品条形码或输入商品名称搜索商品',
		 'INDEX_NOTE_PLACE':'请填写备注信息',
		 'INDEX_PHONE_PLACE':'请输入手机号',
		 'CHANGE_ORDER_NOT_FIND':'未找到相关订单',
		 'CHANGE_SEARCH_PLACE':'扫描条形码 / 输入单号 /输入会员手机号',
		 'CHANGE_SHOP_HUAN':'换货',
		 'CHANGE_SHOP_TUI':'退货',
		 'CHANGE_SHOP_DAMAGED':'货物破损',
		 'CHANGE_ORDER_NOT_FIND':'未找到订单',
		 'CHANGE_USER':'普通用户',
		 'CHANGE_CHOSE':'选择',
		 'CHANGE_SHOP_REASON':'请选择退换货原因',
		 'CHANGE_ORDER_SUCCESS':'退换货成功',
		 'COUNT_ORDER_USER':'普通用户',
		 'COUNT_VIP_RECHARGE':'充值',
		 'COUNT_VIP_REG':'注册',
		 'COUNT_DATE':'日期',
		 'COUNT_OEDER_AND_PHONE':'单号或会员手机号',
		 'LOCK_PASS_ERROR':'密码错误',
		 'LOCK_NO_PASS':'请输入密码',
		 'LOCK_SUCCESS':'解锁成功',
		 'MEMBER_NO_USER':'未找到该用户',
		 'MEMBER_USER_DISABLED':'该用户被禁用',
		 'ORDER_NUM':'数量',
		 'ORDER_TOTAL':'合计',
		 'ORDER_YOUHUI':'优惠',
		 'ORDER_YINGFU':'应付',
		 'ORDER_QUDAN':'取单',
		 'ORDER_DELETE':'删除',
		 'ORDER_YUE':'余额',
		 'ORDER_ZHEKOU':'折扣'
		 
	},
	'english':{
		
	}
}

function lang(type){
	return SITE_I18N[SITE_LANG][type];
}


function pop(type) {
    $('.popbg').show();
    $('.popbg').on('click',function (e) {
        e.stopPropagation();
        $(this).hide();
    });
    $('.popbox').on('click',function (e) {
        e.stopPropagation();
    });
    $('.leftButton').on('click',function () {
        $('.popbg').hide();
    });
}
//提示框
function  tip(msg) {
    $('.tip').show().html(msg);
    setTimeout(function () {
            $('.tip').hide();
        }
    ,2000)
}

//分页
function paginate(total,page,callback){
    total = parseInt(total);
    page = parseInt(page);
    if(total<2){
        return '';
    }
    var pid = 'page-'+Math.round(Math.random()*10000000);
    var html = '<ul id="pagination">';
    if(page != 1){
        html += '<li><a href="javascript:;" aria-label="Previous" class="page-prev">&laquo;</a></li>';
    }else{
        html += '<li class="disabled"><a href="javascript:;" aria-label="Previous" class="page-prev">&laquo;</a></li>';
    }
    if(page > 4){
        html += '<li><a href="javascript:;" class="page-target">1</a></li>';
        html += '<li class="disabled"><a href="javascript:;">...</a></li>';
    }
    var start = 1;
    var end = 5;
    start = page-2;
    end = page+2;
//  if(start > total-5) start = total-5;
    if(start < 1) start = 1;
    if(end<6) end = 6;
    if(end>total) end = total;
    for (var i = start; i <= end; i++) {
        html += '<li class="'+(i==page?'active page-active':'')+'"><a href="javascript:;" class="page-target">'+i+'</a></li>';
    };

    if(total-page>3){
        html += '<li class="disabled"><a href="javascript:;">...</a></li>';
        html += '<li><a href="javascript:;" class="page-target">'+total+'</a></li>';
    }
    if(page != total){
        html += '<li><a href="javascript:;" aria-label="Next" class="page-next">&raquo;</a></li>';
    }else{
        html += '<li class="disabled"><a href="javascript:;" aria-label="Next" class="page-next">&raquo;</a></li>';
    }
    html += '</ul>';
    
    return html;
}

function loadProperties() {
    $.i18n.properties({
        name:'lang',
        path:'../language/',
        mode:'map',
        language:'en_US',
        callback:function(){
            $("[data-locale]").each(function(){
                $(this).html($.i18n.prop($(this).data("locale")));
            });
        }
    });
}

/*加载年份*/
function years(obj, Cyear) {
    var len = 80; // select长度,即option数量
    var selObj = document.getElementById(obj);
    var selIndex = len - 1;
    var newOpt; // OPTION对象

    // 循环添加OPION元素到年份select对象中
    for (i = 1; i <= len; i++) {
        if (selObj.options.length != len) { // 如果目标对象下拉框升度不等于设定的长度则执行以下代码
            newOpt = window.document.createElement("OPTION"); // 新建一个OPTION对象
            newOpt.text = Cyear - len + i; // 设置OPTION对象的内容
            newOpt.value = Cyear - len + i; // 设置OPTION对象的值
            selObj.options.add(newOpt, i); // 添加到目标对象中
        }

    }
}

function months(){
    var month = document.getElementById("month");
    month.length = 0;
    for (i = 1; i < 13; i++) {
        month.options.add(new Option(i, i));
    }

}


function change_date(){
    // var birthday = document.birthday;
    var year  = document.getElementById("year");
    var month = document.getElementById("month");
    var day   = document.getElementById("date");
    vYear  = parseInt(year.value);
    vMonth = parseInt(month.value);
    date.length=0;

    //根据年月获取天数
    var max = (new Date(vYear,vMonth, 0)).getDate();
    for (var i=1; i <= max; i++) {
        date.options.add(new Option(i, i));
    }
}

//锁定
function lock(){
	$('.nav-lock').on('click',function () {
	    $('.popbg').show();
	    $('.popbox').on('click',function (e) {
	        e.stopPropagation();
	    });
	   
	    $('#lock').show().siblings().hide();
	    $('.lock-input')[0].focus();
	});
	$('.lock-btn').click(function(){
		if(!$('.lock-input').val()){
			tip(lang('LOCK_NO_PASS'));
			return;
		}
		var data={password:$('.lock-input').val()}
		$.ajax({
			type:'POSt',
			data:data,
			dataType:'json',
			url:urlHead+'/user/unlock',
			success:function(json){
				$('.popbg').hide();
				$('.lock-input').val('');
				tip(lang('LOCK_SUCCESS'))
			},
			error:function(res){
				if(res.status == 500){
					tip(lang('LOCK_PASS_ERROR'))
				}
			}
		})
	})
}
 
function toAdd(n) {
    n = n.toString();
    return n[1] ? n : '0' + n
}

function getTime() {
    var time=new Date();
    var year=time.getFullYear();
    var month=time.getMonth()+1;
    var day=time.getDate();
    var hour=time.getHours();
    var min=time.getMinutes();
    var second=time.getSeconds();
    var str=toAdd(day)+'-'+toAdd(month)+'-'+year+' '+toAdd(hour)+':'+toAdd(min)+':'+toAdd(second);
    return str;
}


function OrderPushClient() {
  this.config = this.default_config;
  // 监听者
  this.listeners = {

  };
  // websocket 客户端
  this.ws = null;
  // 心跳interval id
  this.heartBeatId = null;
}

OrderPushClient.prototype.default_config = {
  host: '47.91.72.8',
  port: '31675'
};

OrderPushClient.prototype.on = function (event_name, handler) {
  if (!this.listeners.hasOwnProperty(event_name)) {
    this.listeners[event_name] = [];
  }

  this.listeners[event_name].push(handler);
};

OrderPushClient.prototype.connect = function () {
  this.ws = new WebSocket('ws://'+this.config.host+':'+this.config.port);
};

OrderPushClient.prototype.heartBeat = function () {
  if (null === this.ws) {
    throw new Error('webSocket not connect');
  }

  this.ws.onerror = (function () {
    clearInterval(this.heartBeatId);
  }).bind(this);

  var call = function () {
    this.ws.send(JSON.stringify({
        'method': 'get',
        'route': '/client/heartBeat',
        'request': {
        }
    }));
  };
  setInterval(call.bind(this), 5000);
};

// 解析message 分发事件
OrderPushClient.prototype.parsedMessage = function () {
  this.ws.onmessage = (function (e) {
    try {
      var data = JSON.parse(e.data);
    } catch (e) {
      throw e;
    }
    var eventName = data.event;
    var payload = data.payload;
    var event = {
      eventName: eventName,
      data: payload,
      ws: this.ws
    };
    if (this.listeners.hasOwnProperty(eventName)) {
      for(var k in this.listeners[eventName]) {
        let handler = this.listeners[eventName][k];
        handler(event);
      }
    }
  }).bind(this);
};

OrderPushClient.prototype.start = function () {
  this.connect();
  this.parsedMessage();
  this.heartBeat();
};

OrderPushClient.prototype.stop = function () {
  this.ws.close();
};
//线上订单打印
var online = new OrderPushClient();
online.start();
online.on('orderCreated', function (e) {
    console.log(e.data.order_id);
    var id=e.data.order_id;
    $.ajax({
		type:'GET',
		dataType:'json',
		url:urlHead+'/order/get_order/'+id,
		success:function(json){
			console.log(json)
            $('#online').show().siblings().hide();
            var deliveryTime=json.order.shipping_date+' '+json.order.shipping_time;
			var paymode = SITE_CONFIG.pay_types[0][SITE_LANG];
            if(json.order.money == 0) paymode = '';
            if(json.order.pay_mode>0) paymode+= SITE_CONFIG.pay_types[json.order.pay_mode][SITE_LANG];
      
			$('#online .cashier-name').html( CASHIER);
			$('#online .order-time').html(json.order.create_time);
			$('#online .order_id').html(json.order.order_id);
			$('#online .print-order-payMode').html(paymode+'支付');
			$('#online .delivery-time').html(deliveryTime);
			var list=''
			var count=0;
			$.each(json.items,function(index,item){
				count+=Number(item.qty);
				list+='<div class="print-table-list">'
					+'<div class="print-food">'+(index+1)+'.'+item.product.title+'</div>'
					+'<div class="print-food-detail">'
					+	'<span>'+item.price+'</span>'
					+	'<span>'+item.qty+'</span>'
					+	'<span>'+item.total+'</span>'
					+'</div>'
				+'</div>'
			})
			$('#online .print-table-body').html(list);
			$('#online .print-table-total-food').html(count.toFixed(2));
			$('#online .print-table-total-price').html(json.order.total);
			if(json.user){
				var user=json.user;
				$('#online .vip-name').html(user.username);
				$('#online .vip-weixin').html(user.wechat);
				$('#online .vip-address').html((json.order.address.address?json.order.address.address:user.address));
				$('#online .vip-zip').html(user.zip);
				$('#online .vip-phone').html(user.phone);
			}else{
				$('#online .vip-name-box').html('联系姓名：');
			}
			var consumption='';
			consumption+='<div class="print-list" >消费金额：'+json.order.total+'</div>'
					+'<div class="print-list" >优惠金额：'+json.order.cut_fee+'</div>'
			
			if(json.order.user_id > 0){
				consumption+='<div class="print-list" >会员支付：'+json.order.money+'</div>'
				if(json.order.pay_fee>0){
					consumption+='<div class="print-list" >'+SITE_CONFIG.pay_types[json.order.pay_mode][SITE_LANG]+'支付：'+json.order.pay_fee+'</div>'
				}	
				consumption+='<div class="print-list" >上次余额：'+json.order.last+'</div>'
							+'<div class="print-list" >当前余额：'+json.order.now+'</div>'
			}else{
				consumption+='<div class="print-list" >'+paymode+'支付：'+json.order.pay_fee+'</div>'
			}
					
			$('.consumption').html(consumption);
			
			var vatNet=parseFloat(json.order.total)-parseFloat(json.order.cut_fee)-parseFloat(json.order.vat);
			var vatGross=parseFloat(json.order.total)-parseFloat(json.order.cut_fee);
			$('#online .vat-net').html(vatNet.toFixed(2));
			$('#online .vat-20').html(json.order.vat);
			$('#online .vat-gross').html(vatGross.toFixed(2));
			$('.print-time-detail').html(getTime())
			$('#online').jqprint();
		}
	})
});
